package com.enation.app.javashop.core.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.shop.model.dto.ReceiveTimeCalDTO;
import com.enation.app.javashop.core.shop.model.vo.FixReceiveTimeVO;
import com.enation.app.javashop.core.shop.model.dto.FixTimeDispatchSetting;
import com.enation.app.javashop.core.shop.model.dto.FixTimeSection;
import com.enation.app.javashop.core.shop.model.vo.ReceiveTimeVO;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.util.DictUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JFeng
 * @date 2020/11/23 17:35
 */
@Service
public class OrderReceiveTimeManager {

    @Autowired
    private Cache cache;

    private final String RECEIVE_TIME="{RECEIVE_TIME}_";

    /**
     * 用户可选配送时间段
     * @param sellerId
     * @param county
     * @return
     */
    public ReceiveTimeVO getTimeSectionBySeller(Integer sellerId, String county ,String shippingType) {

        ReceiveTimeCalDTO receiveTimeCalDTO = executeReceiveTimeCal(sellerId);

        ReceiveTimeVO receiveTimeVO= receiveTimeCalDTO.transToReceiveTimeVO(county,shippingType);

        return receiveTimeVO;
    }

    private ReceiveTimeCalDTO executeReceiveTimeCal(Integer sellerId) {
        // 先从redis中获取半日达时效配置 没有从MySQL中获取
        ReceiveTimeCalDTO receiveTimeCalDTO =(ReceiveTimeCalDTO)cache.get(RECEIVE_TIME+sellerId);
        if(receiveTimeCalDTO==null){
            FixTimeDispatchSetting fixTimeDispatchSetting = getFixTimeDispatchSetting(sellerId);
            receiveTimeCalDTO = new ReceiveTimeCalDTO(fixTimeDispatchSetting);
            receiveTimeCalDTO.kickOffExceptDay();
            cache.put(RECEIVE_TIME+sellerId,receiveTimeCalDTO,60);
        }
        return receiveTimeCalDTO;
    }


    /**
     * 根据选中的配送时间点 计算实际送达时间
     * @param sellerId
     * @param receiveTimeSeq
     * @return
     */
    public FixTimeSection getReceiveTimeBySeller(int sellerId, Integer receiveTimeSeq) {
        ReceiveTimeCalDTO receiveTimeCalDTO = executeReceiveTimeCal(sellerId);
        receiveTimeSeq = receiveTimeSeq == null || receiveTimeSeq == 0  ? receiveTimeCalDTO.getDefaultSeq() : receiveTimeSeq;
        receiveTimeCalDTO.calculateSelectedReceiveTime(receiveTimeSeq);
        return new FixTimeSection(receiveTimeCalDTO.getReceiveTimeStamp(),receiveTimeCalDTO.getReceiveTimeType());
    }


    /**
     * 出库可选分拣时段
     * @param sellerId
     * @return
     */
    public List<FixTimeSection> getSortBatchList(Integer sellerId) {
        Integer nowTime = Integer.valueOf(LocalTime.now().getHour()*100+ LocalTime.now().getMinute());
        FixTimeDispatchSetting dispatchSetting = this.getFixTimeDispatchSetting(sellerId);
        if(dispatchSetting==null){
            return new ArrayList<>();
        }
        // 次日配送时间段
        List<FixTimeSection> timeSections = dispatchSetting.getTimeSections();
        if(CollectionUtils.isEmpty(timeSections)){
            timeSections= Arrays.asList(dispatchSetting.getDefaultTimeSection());
        }

        List<FixTimeSection> fixTimeSections = timeSections.stream().filter(fixTimeSection -> fixTimeSection.getReceiveTimeType() == 0 || (fixTimeSection.getReceiveTimeType() == 1 && fixTimeSection.getEndOrderTime() < nowTime)).collect(Collectors.toList());

        return fixTimeSections;

    }

    private FixTimeDispatchSetting getFixTimeDispatchSetting(Integer sellerId) {
        String settingJson = DictUtils.getDictValue(null, CachePrefix.FIX_TIME_DISPATCH.getPrefix() + sellerId, CachePrefix.FIX_TIME_DISPATCH.getPrefix());
        if (StringUtils.isEmpty(settingJson)) {
            return null;
        }
        return JSON.parseObject(settingJson, FixTimeDispatchSetting.class);
    }

    /**
     * 出库管理 查询获取对应分拣时间
     * @param sellerId
     * @param receiveTimeSeq
     * @return
     */
    public FixTimeSection resolveReceiveTimeSeq(Integer sellerId, Integer receiveTimeSeq) {
        FixTimeDispatchSetting dispatchSetting = this.getFixTimeDispatchSetting(sellerId);
        List<FixTimeSection> timeSections = dispatchSetting.getTimeSections();
        if (!CollectionUtils.isEmpty(timeSections)) {
            timeSections = timeSections.stream().filter(fixTimeSection -> fixTimeSection.getSeq().equals(receiveTimeSeq)).collect(Collectors.toList());
        }
        FixTimeSection selectedTime = CollectionUtils.isEmpty(timeSections) ? dispatchSetting.getDefaultTimeSection() : timeSections.get(0);

        LocalTime localTime = LocalTime.of(selectedTime.getReceiveTime() / 100 % 100, selectedTime.getReceiveTime() % 100);

        LocalDateTime lastDayEndTime = LocalDateTime.of(LocalDate.now(), localTime);
        Long receiveTime = lastDayEndTime.toInstant(ZoneOffset.of("+8")).toEpochMilli() / 1000;
        selectedTime.setReceiveTimeStamp(receiveTime);
        return selectedTime;
    }
}
